package com.kristin.util;

import com.google.gson.Gson;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import sun.net.www.http.HttpClient;

import java.io.OutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

/**
 * @ClassName RemoteFactory
 * @Description TODO
 * @Author Kristin
 * @Date 2021/06/23 16:13:11
 * @Version 1.0.0
 */
public class RemoteFactory {

    static Gson gson = new Gson();


    public static Object getRemoteObject(Class clazz) {
        final String className = clazz.getName();
        InvocationHandler invocationHandler = new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("远程方法调用");

                String requestStr = "http://localhost:8081/dispatcher?";
                String suffix = "serverName=" + className + "&methodName=" + method.getName();

                suffix = URLEncoder.encode(suffix , "utf-8");

                requestStr = requestStr + suffix;

                System.out.println(requestStr);
                URL url = new URL(requestStr);
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(url)
                        .get()
                        .build();
                Response response = client.newCall(request).execute();
                return response.body().string();
            }
        };

        Object o = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, invocationHandler);
        return o;
    }

}
